package com.leetcode;

public class L0566 {
    public static void main(String[] args) {
        int[][] mar={{1,2},{3,4}};
        int[][] ints = matrixReshape(mar, 1, 4);
        for (int[] anInt : ints) {
            for (int i : anInt) {
                System.out.print(i);
            }
            System.out.println();
        }
    }
//    public int[][] matrixReshape(int[][] nums, int r, int c) {
//        int m = nums.length;
//        int n = nums[0].length;
//        if (m * n != r * c) {
//            return nums;
//        }
//
//        int[][] ans = new int[r][c];
//        for (int x = 0; x < m * n; ++x) {
//            ans[x / c][x % c] = nums[x / n][x % n];
//        }
//        return ans;
//    }

    public static int[][] matrixReshape(int[][] mat, int r, int c) {
        int countLength=mat[0].length*mat.length;
        if (r*c!=countLength){
            return mat;
        }
        int[][] res=new int[r][c];
        int hang=0,lie=0;
        for (int i=0;i<mat.length;i++){
            for (int j=0;j<mat[0].length;j++){
                 if (lie<c)
                     res[hang][lie++]=mat[i][j];
                 else {
                     hang++;
                     lie=0;
                     res[hang][lie]=mat[i][j];
                 }
            }
        }
        return res;
    }
}
